package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;
import com.sky.constant.Constants;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;

import com.sky.manager.AsyncManager;
import com.sky.manager.factory.AsyncFactory;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageBean;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.BcriptUtils;
import com.sky.utils.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            // 记录登录失败日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(employeeLoginDTO.getUsername(), Constants.LOGIN_FAIL,
                    MessageUtils.message("the.user.does.not.exist")));
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!BcriptUtils.checkPassword(password, employee.getPassword())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(employeeLoginDTO.getUsername(), Constants.LOGIN_FAIL,
                    MessageUtils.message("wrong.password")));
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(employeeLoginDTO.getUsername(), Constants.LOGIN_FAIL,
                    MessageUtils.message("account.locked")));
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 成功日志
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS,
                MessageUtils.message("user.login.success")));


        //3、返回实体对象
        return employee;
    }

    @Override
    public PageBean getEmployees(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        Page page = (Page) employeeMapper.pageEmployee(employeePageQueryDTO.getName());

        PageBean pageBean = new PageBean();
        pageBean.setRecords(page.getResult());
        pageBean.setTotal(page.getTotal());
        return pageBean;
    }

    @Override
    public void addEmp(Employee emp) {
//        emp.setUpdateTime(LocalDateTime.now());
//        emp.setCreateTime(LocalDateTime.now());
        emp.setPassword(BcriptUtils.createPassword(PasswordConstant.DEFAULT_PASSWORD));
        emp.setStatus(StatusConstant.ENABLE);
        // 获取当前线程map中的员工id
//        emp.setCreateUser(BaseContext.getCurrentId());
//        emp.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.addEmp(emp);
    }

    @Override
    public Employee getEmp(String id) {
        Employee emp = employeeMapper.getEmpById(id);
        return emp;
    }

    @Override
    public void updateEmp(Employee emp) {
//        emp.setUpdateUser(BaseContext.getCurrentId());
//        emp.setUpdateTime(LocalDateTime.now());
        employeeMapper.updateEmpById(emp);
    }

    @Override
    public void changeStatus(String status, String id) {
        Employee employee = new Employee();
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setStatus(Integer.valueOf(status));
        employee.setId(Long.valueOf(id));
        employeeMapper.changeStatus(employee);
    }

    @Override
    public boolean editPassword(PasswordEditDTO password) {
        Employee empById = employeeMapper.getEmpById(String.valueOf(BaseContext.getCurrentId()));
        if (BcriptUtils.checkPassword(password.getOldPassword(), empById.getPassword())) {
            String newPassword = BcriptUtils.createPassword(password.getNewPassword());
            password.setEmpId(BaseContext.getCurrentId());// 设置id
            employeeMapper.editPassword(String.valueOf(password.getEmpId()), newPassword);
            return true;
        } else {
            return false;
        }
    }


}
